package com.ajocer.springbootinit.monitor;

import com.ajocer.springbootinit.rag.MultiLayerCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 缓存性能监控服务
 * 监控缓存命中率、查询延迟和API调用成本
 */
@Service
@Slf4j
public class CachePerformanceMonitor {

    @Autowired
    private MultiLayerCacheService cacheService;
    
    // 计数器
    private AtomicLong totalRequestsCounter = new AtomicLong(0);
    private AtomicLong cacheHitsCounter = new AtomicLong(0);
    private AtomicLong apiCallsCounter = new AtomicLong(0);
    
    // 成本统计
    private AtomicLong totalApiCost = new AtomicLong(0);
    private AtomicLong savedApiCost = new AtomicLong(0);
    
    // 平均查询延迟（毫秒）
    private AtomicLong totalLatency = new AtomicLong(0);
    private AtomicLong requestCount = new AtomicLong(0);
    
    // API调用成本（元/次）
    private static final double API_CALL_COST = 0.01;
    
    public void init() {
        log.info("缓存性能监控服务初始化完成");
    }
    
    /**
     * 记录请求
     * @param isCacheHit 是否缓存命中
     * @param latencyMs 延迟（毫秒）
     */
    public void recordRequest(boolean isCacheHit, long latencyMs) {
        totalRequestsCounter.incrementAndGet();
        totalLatency.addAndGet(latencyMs);
        requestCount.incrementAndGet();
        
        if (isCacheHit) {
            cacheHitsCounter.incrementAndGet();
            savedApiCost.addAndGet((long) (API_CALL_COST * 100)); // 转换为分
        } else {
            apiCallsCounter.incrementAndGet();
            totalApiCost.addAndGet((long) (API_CALL_COST * 100)); // 转换为分
        }
    }
    
    /**
     * 获取缓存命中率
     */
    public double getCacheHitRate() {
        double totalRequests = totalRequestsCounter.get();
        if (totalRequests == 0) {
            return 0;
        }
        return cacheHitsCounter.get() / totalRequests;
    }
    
    /**
     * 获取平均查询延迟（毫秒）
     */
    public double getAverageLatency() {
        long count = requestCount.get();
        if (count == 0) {
            return 0;
        }
        return (double) totalLatency.get() / count;
    }
    
    /**
     * 获取API成本节省率
     */
    public double getApiCostSavingRate() {
        long totalCost = totalApiCost.get() + savedApiCost.get();
        if (totalCost == 0) {
            return 0;
        }
        return (double) savedApiCost.get() / totalCost;
    }
    
    /**
     * 定时打印性能报告
     */
    @Scheduled(fixedRate = 3600000) // 每小时执行一次
    public void printPerformanceReport() {
        double cacheHitRate = getCacheHitRate() * 100;
        double averageLatency = getAverageLatency();
        double costSavingRate = getApiCostSavingRate() * 100;
        
        log.info("缓存性能报告:");
        log.info("总请求数: {}", totalRequestsCounter.get());
        log.info("缓存命中率: {:.2f}%", cacheHitRate);
        log.info("平均查询延迟: {:.2f}ms", averageLatency);
        log.info("API调用次数: {}", apiCallsCounter.get());
        log.info("API成本节省率: {:.2f}%", costSavingRate);
        log.info("缓存统计: {}", cacheService.getCacheStats());
    }
} 